import glob
import os
import tkinter as tk
from tkinter import messagebox
from PIL import Image, ImageTk, ImageDraw
import keyboard
import math


def find_png_files(directory):
    png_files = glob.glob(os.path.join(directory, '**', '*.png'), recursive=True)
    return png_files


# 创建窗口
root = tk.Tk()
root.title("序列帧播放器")
root.config(bg="grey")
root.geometry("1000x1000")

# background_image = Image.open("D:/Users/admin/Downloads/composite/body_output/50001_ATTACK_0/0.png")
# background_photo = ImageTk.PhotoImage(background_image)
# canvas.
# 暂停修改--将index保持不动，一直重复刷同一帧

global offX, offY
offX = 60
offY = 50
tk.Label(root,text="请输入文件夹路径", bg='green').place(x=offX, y=2)
tk.Label(root,text="勾选复选框启用锚点修改功能", bg='green').place(x=offX, y=20)

check_var = tk.IntVar()
check_var1 = tk.IntVar()
check_var2 = tk.IntVar()
check_var3 = tk.IntVar()


def check_status():
    if check_var.get():
        return 'on'
    else:
        return 'off'


def check_status1():
    if check_var1.get():
        return 'on'
    else:
        return 'off'


def check_status2():
    if check_var2.get():
        return 'on'
    else:
        return 'off'


# 输入框一
entry_var = tk.StringVar()
entry_path = tk.Entry(root, textvariable=entry_var)
check_anchor = tk.Checkbutton(root, variable=check_var).place(x=offX + 150, y=offY - 3)
entry_path.place(x=offX, y=offY)

tk.Label(root,text="请输入模型ID或模型ID具体动作", bg='green').place(x=offX, y=offY + 85)
entry_role = tk.StringVar()
entry_rolename = tk.Entry(root, textvariable=entry_role)
entry_rolename.place(x=offX, y=offY + 113)
# 输入框二
entry_var1 = tk.StringVar()
entry_path1 = tk.Entry(root, textvariable=entry_var1)
check_anchor1 = tk.Checkbutton(root, variable=check_var1).place(x=offX + 350, y=offY - 3)
entry_path1.place(x=offX + 200, y=offY)

tk.Label(root,text="请输入技能ID", bg='green').place(x=offX + 200, y=offY + 85)
entry_skill = tk.StringVar()
entry_skillname = tk.Entry(root, textvariable=entry_skill)
entry_skillname.place(x=offX + 200, y=offY + 113)
# 输入框三
entry_var2 = tk.StringVar()
entry_path2 = tk.Entry(root, textvariable=entry_var2)
check_anchor2 = tk.Checkbutton(root, variable=check_var2).place(x=offX + 550, y=offY - 3)
entry_path2.place(x=offX + 400, y=offY)

tk.Label(root,text="请输入武器ID或武器ID具体动作", bg='green').place(x=offX + 400, y=offY + 85)
entry_wuqi = tk.StringVar()
entry_wuqiname = tk.Entry(root, textvariable=entry_wuqi)
entry_wuqiname.place(x=offX + 400, y=offY + 113)


# 切换指定ID角色
def change_role():
    global role_button, role_name, directory_type, cur_frame_index
    role_name = entry_role.get()
    directory_type = []
    # index = 0
    for item in all_directory_type:
        for name in item:
            if role_name in name:
                directory_type.append(name)
                # cur_directory_type_index = index
                # return
        # index+=1
    load_images_from_directory1()
    cur_frame_index = 0


# 切换指定ID技能
def change_skill():
    global skill_button, skill_name, directory_type1, cur_frame_index
    skill_name = entry_skill.get()
    directory_type1 = []
    # index = 0
    for item in all_directory_type1:
        for name in item:
            if skill_name in name:
                # cur_directory_type_index1 = index
                directory_type1.append(name)
                # return
        # index+=1
    load_images_from_directory2()
    cur_frame_index = 0


# 切换指定ID武器
def change_wuqi():
    global wuqi_button, wuqi_name, directory_type2, cur_frame_index
    wuqi_name = entry_wuqi.get()
    directory_type2 = []
    # index = 0
    for item in all_directory_type2:
        for name in item:
            if wuqi_name in name:
                # cur_directory_type_index2 = index
                directory_type2.append(name)
                # return
        # index+=1
    load_images_from_directory3()
    cur_frame_index = 0


role_button = tk.Button(root, text="加载指定ID模型", command=change_role, bg='skyblue').place(x=offX, y=offY + 140)
skill_button = tk.Button(root, text="加载指定ID技能", command=change_skill, bg='red').place(x=offX + 200, y=offY + 140)
wuqi_name = tk.Button(root, text="加载指定ID武器", command=change_wuqi, bg='orange').place(x=offX + 400, y=offY + 140)

global image_frames, image_frames1, image_frames2, image_frames3, cur_frame_index, cur_directory_type_index, input_x, input_y, input_x_value, input_y_value
input_x = 0
input_y = 0
input_x_value = 0
input_y_value = 0
image_frames = []
image_frames1 = []
image_frames2 = []
image_frames3 = []
cur_directory_type_index = 0
cur_frame_index = 0

global speed
speed=100

# 从目录加载图片
def load_images_from_directory():
    global image_frames, image_frames1, image_frames2, image_frames3, cur_frame_index, cur_directory_type_index
    image_paths = []
    for i, d in enumerate(all_directory_type[cur_directory_type_index]):
        image_paths.extend(find_png_files(image_frames_path + "/" + d))

    if not image_paths:
        messagebox.showerror("Error", "目录一没有图片文件")

    if image_frames_path1 != '':
        image_paths1 = []
        for i, d in enumerate(all_directory_type1[cur_directory_type_index1]):
            image_paths1.extend(find_png_files(image_frames_path1 + "/" + d))
        image_frames1 = [Image.open(path) for path in image_paths1]

    if image_frames_path2 != '':
        image_paths2 = []
        for i, d in enumerate(all_directory_type2[cur_directory_type_index2]):
            image_paths2.extend(find_png_files(image_frames_path2 + "/" + d))
        image_frames2 = [Image.open(path) for path in image_paths2]

    cur_frame_index = 0
    image_frames = [Image.open(path) for path in image_paths]
    reset_window()

    # 从目录加载指定动作图片


def load_images_from_directory1():
    global image_frames, cur_frame_index, cur_directory_type_index, directory_type
    image_paths = []
    for i, d in enumerate(directory_type):
        image_paths.extend(find_png_files(image_frames_path + "/" + d))
    if not image_paths:
        messagebox.showerror("Error", "目录一没有图片文件")
    cur_frame_index = 0
    image_frames = [Image.open(path) for path in image_paths]
    reset_window()


def load_images_from_directory2():
    global image_frames1, cur_frame_index, directory_type1
    if image_frames_path1 != '':
        image_paths1 = []
        for i, d in enumerate(directory_type1):
            image_paths1.extend(find_png_files(image_frames_path1 + "/" + d))
        image_frames1 = [Image.open(path) for path in image_paths1]
        cur_frame_index = 0
        reset_window()


def load_images_from_directory3():
    global image_frames2, cur_frame_index, directory_type2
    if image_frames_path2 != '':
        image_paths2 = []
        for i, d in enumerate(directory_type2):
            image_paths2.extend(find_png_files(image_frames_path2 + "/" + d))
        image_frames2 = [Image.open(path) for path in image_paths2]
        cur_frame_index = 0
        reset_window()


# 获取输入路径
def get_input_path():
    global image_frames, last_button, next_button, image_frames_path, image_frames_path1, image_frames_output_path, image_frames_output_path1
    global all_directory_type, all_directory_type1, cur_directory_type_index, cur_directory_type_index1
    # 路径一
    all_directory_type = []
    cur_directory_type_index = 0
    image_frames_path = entry_var.get().replace("\\", "/")
    if image_frames_path != '':
        image_frames_output_path = image_frames_path + "_output"
        all_directory = [d for d in os.listdir(image_frames_path) if os.path.isdir(os.path.join(image_frames_path, d))]
        dir_name = ""
        for i, d in enumerate(all_directory):
            net_dir_name = os.path.basename(d)
            if dir_name.split("_")[0] == net_dir_name.split("_")[0]:
                all_directory_type[-1].append(net_dir_name)
            else:
                dir_name = net_dir_name
                all_directory_type.append([dir_name])

    if not all_directory_type:
        messagebox.showerror("Error", "路径一没有目录")
        # return
    # 路径二
    all_directory_type1 = []
    cur_directory_type_index1 = 0
    image_frames_path1 = entry_var1.get().replace("\\", "/")
    if image_frames_path1 != '':
        image_frames_output_path1 = image_frames_path1 + "_output"
        all_directory1 = [d for d in os.listdir(image_frames_path1) if
                          os.path.isdir(os.path.join(image_frames_path1, d))]
        dir_name1 = ""
        for i, d in enumerate(all_directory1):
            net_dir_name1 = os.path.basename(d)
            if dir_name1.split("_")[0] == net_dir_name1.split("_")[0]:
                all_directory_type1[-1].append(net_dir_name1)
            else:
                dir_name1 = net_dir_name1
                all_directory_type1.append([dir_name1])

    # 路径三
    global all_directory_type2, cur_directory_type_index2, image_frames_path2, image_frames_output_path2
    all_directory_type2 = []
    cur_directory_type_index2 = 0
    image_frames_path2 = entry_var2.get().replace("\\", "/")
    if image_frames_path2 != '':
        image_frames_output_path2 = image_frames_path2 + "_output"
        all_directory2 = [d for d in os.listdir(image_frames_path2) if
                          os.path.isdir(os.path.join(image_frames_path2, d))]
        dir_name2 = ""
        for i, d in enumerate(all_directory2):
            net_dir_name2 = os.path.basename(d)
            if dir_name2.split("_")[0] == net_dir_name2.split("_")[0]:
                all_directory_type2[-1].append(net_dir_name2)
            else:
                dir_name2 = net_dir_name2
                all_directory_type2.append([dir_name2])

    load_images_from_directory()

get_input_button = tk.Button(root, text="加载图片", command=get_input_path,bg='skyblue')
get_input_button.place(x=offX+200,y=offY - 40)


def btn_last_directory():
    global cur_directory_type_index, cur_directory_type_index1
    if cur_directory_type_index <= 0:
        messagebox.showerror("Error", "没有了")
        return
    cur_directory_type_index -= 1
    load_images_from_directory()


def btn_next_directory():
    global cur_directory_type_index
    if cur_directory_type_index >= len(all_directory_type) - 1:
        messagebox.showerror("Error", "没有了")
        return
    cur_directory_type_index += 1
    load_images_from_directory()


last_button = tk.Button(root, text="上一个", command=btn_last_directory)
last_button.place(x=offX + 10, y=offY + 40)
next_button = tk.Button(root, text="下一个", command=btn_next_directory)
next_button.place(x=offX + 90, y=offY + 40)

# 按钮，上下切换图片资源二
global last_button1, next_button1


def btn_last_directory1():
    global cur_directory_type_index1
    if cur_directory_type_index1 <= 0:
        messagebox.showerror("Error", "没有了")
        return
    cur_directory_type_index1 -= 1
    load_images_from_directory()


def btn_next_directory1():
    global cur_directory_type_index1
    if cur_directory_type_index1 >= len(all_directory_type1) - 1:
        messagebox.showerror("Error", "没有了")
        return
    cur_directory_type_index1 += 1
    load_images_from_directory()


last_button1 = tk.Button(root, text="上一个", command=btn_last_directory1)
last_button1.place(x=offX + 210, y=offY + 40)
next_button1 = tk.Button(root, text="下一个", command=btn_next_directory1)
next_button1.place(x=offX + 290, y=offY + 40)

# 按钮，上下切换图片资源三
global last_button2, next_button2


def btn_last_directory2():
    global cur_directory_type_index2
    if cur_directory_type_index2 <= 0:
        messagebox.showerror("Error", "没有了")
        return
    cur_directory_type_index2 -= 1
    load_images_from_directory()


def btn_next_directory2():
    global cur_directory_type_index2
    if cur_directory_type_index2 >= len(all_directory_type2) - 1:
        messagebox.showerror("Error", "没有了")
        return
    cur_directory_type_index2 += 1
    load_images_from_directory()


last_button1 = tk.Button(root, text="上一个", command=btn_last_directory2)
last_button1.place(x=offX + 410, y=offY + 40)
next_button1 = tk.Button(root, text="下一个", command=btn_next_directory2)
next_button1.place(x=offX + 490, y=offY + 40)

# 图像绘制位置坐标
canvas = tk.Canvas(root, width=800, height=800, bg="gray")
canvas.place(x=offX + 70, y=offY + 180)


# 重置窗口
def reset_window():
    global image_max_width, image_max_height, canvas_width, canvas_height, center_x, center_y, cur_frame_index
    image_max_width = 0
    image_max_height = 0
    canvas_width = 750
    canvas_height = 800
    center_x = 0
    center_y = 0
    cur_frame_index = 0
    for i, img in enumerate(image_frames):
        image_max_width = max(image_max_width, img.width)
        image_max_height = max(image_max_height, img.height)

    root_width = max(canvas_width, image_max_width)
    root_height = max(canvas_height, image_max_height)
    # 处理大图
    root.geometry(f"{root_width}x{root_height}")
    canvans_width = max(512, image_max_width)
    canvans_height = max(512, image_max_height)
    canvas.config(width=800, height=800)
    center_x = canvas_width / 2
    center_y = canvas_height / 2

# 鼠标指针样式
def on_canvas_enter(event):
    event.widget.config(cursor="tcross")


def on_canvas_leave(event):
    event.widget.config(cursor="")


canvas.bind("<Enter>", on_canvas_enter)
canvas.bind("<Leave>", on_canvas_leave)

def update_frame():
    global photo_image, photo_image1,photo_image2,photo_image3,cur_frame_index, root_after,path_index1,image_name
    global input_x, input_y
    if image_frames:
        #目录一
        if  cur_frame_index >= len(image_frames):
            path_index = len(image_frames) - 1
            image_frame = image_frames[path_index]
            photo_image = ImageTk.PhotoImage(image_frame)
        else:
            image_frame = image_frames[cur_frame_index]
            photo_image = ImageTk.PhotoImage(image_frame)
        #目录二
        if image_frames_path1 != '':
            if cur_frame_index >= len(image_frames1):
                path_index1 = len(image_frames1)-1
                image_frame1 = image_frames1[path_index1]
                photo_image1 = ImageTk.PhotoImage(image_frame1)
            else:
                image_frame1 = image_frames1[cur_frame_index]
                photo_image1 = ImageTk.PhotoImage(image_frame1)
        #目录三
        if image_frames_path2 != '':
            if cur_frame_index >= len(image_frames2):
                path_index2 = len(image_frames2)-1
                image_frame2 = image_frames2[path_index2]
                photo_image2 = ImageTk.PhotoImage(image_frame2)
            else:
                image_frame2 = image_frames2[cur_frame_index]
                photo_image2 = ImageTk.PhotoImage(image_frame2)

        canvas.delete("all")  # 清除之前的图像
        canvas.create_rectangle(center_x-image_frame.width/2, center_y-image_frame.height/2, center_x+image_frame.width/2, center_y+image_frame.height/2, fill="white", outline="black")
        if check_status() == 'on':
            canvas.create_image(center_x + int(input_x), center_y + int(input_y), anchor=tk.CENTER, image=photo_image)
        else:
            canvas.create_image(center_x , center_y, anchor=tk.CENTER, image=photo_image)
        if image_frames_path1 != '':
            if check_status1() == 'on':
                canvas.create_image(center_x+ int(input_x), center_y + int(input_y), anchor=tk.CENTER, image=photo_image1)
            else:
                canvas.create_image(center_x, center_y, anchor=tk.CENTER, image=photo_image1)
        if image_frames_path2 != '':
            if check_status2() == 'on':
                canvas.create_image(center_x+ int(input_x), center_y + int(input_y), anchor=tk.CENTER, image=photo_image2)
            else :
                canvas.create_image(center_x, center_y, anchor=tk.CENTER, image=photo_image2)

        canvas.create_line(0, center_y , canvas_width, center_y, fill="red", width=1)
        canvas.create_line(center_x, 0, center_x, canvas_height, fill="red", width=1)

        #显示当前正在播放的人物，技能和武器动画名称
        image_name = image_frame.filename.replace("\\", "/").replace(image_frames_path, "")
        root.title("人物" + image_name)
        length = len(image_frames)
        if image_frames_path1 != '':
            image_name1 = image_frame1.filename.replace("\\", "/").replace(image_frames_path1, "")
            root.title("人物" + image_name + "   技能" + image_name1)
            length = max(len(image_frames),len(image_frames1))
        if image_frames_path2 != '':
            image_name2 = image_frame2.filename.replace("\\", "/").replace(image_frames_path2, "")
            root.title("人物" + image_name + "   技能" + image_name1 + "   武器" + image_name2)
            length = max(len(image_frames),len(image_frames1),len(image_frames2))

        cur_frame_index = (cur_frame_index + 1) % length  # 循环显示

    root_after = root.after(speed, update_frame)  # 每100毫秒更新一次

#暂停,继续，重置，调速方法
entry_speed = tk.StringVar()
entry_speedvalue = tk.Entry(root,textvariable=entry_speed,width= 7)
entry_speedvalue.place(x=offX,y=offY + 350)
def set_speed_play():
    global stop_button, continue_button, first_frame_button, speed_button,speed
    speed = entry_speed.get()

global isplay
isplay = True
def stop_play():
    global root_after
    global speed,isplay
    if(isplay):
        root.after_cancel(root_after)
    else:
        root_after = root.after(speed, update_frame)
    isplay = not isplay

def continue_play():
    global root_after
    global speed
    root_after = root.after(speed, update_frame)

def restart_play():
    global cur_frame_index
    cur_frame_index = 0

stop_button = tk.Button(root, text="暂停/继续", command= stop_play).place(x=offX,y=offY + 200)
stop_button = tk.Button(root, text="继续播放", command= continue_play).place(x=offX,y=offY + 250)
stop_button = tk.Button(root, text="从头播放", command= restart_play).place(x=offX,y=offY + 300)
stop_button = tk.Button(root, text="调整速度", command= set_speed_play).place(x=offX,y=offY + 380)

#调整量输入框
entry_var_change = tk.StringVar()
entry_path = tk.Entry(root, textvariable=entry_var_change,width=5)
entry_path.place(x=offX + 300,y=offY - 37)

def save_change_input_values():
    global input_x_value, input_y_value
    input_x_value = entry_var_change.get()
    input_y_value = entry_var_change.get()

save_change_input_value = tk.Button(root, text= "调整",command= save_change_input_values,bg="skyblue").place(x=offX + 350,y=offY - 40)

def on_key_event(event):
    global input_x, input_y, input_x_value , input_y_value
    if keyboard.is_pressed('up'):  # 检查是否按下了 '' 键
        input_y -= int(input_y_value)
    if keyboard.is_pressed('down'):
        input_y += int(input_y_value)
    if keyboard.is_pressed('left'):
        input_x -= int(input_x_value)
    if keyboard.is_pressed('right'):
        input_x += int(input_x_value)
        # input_x += input_x
        # print("检测到 right 键！::" + str(input_x))
        # print(f"Key {event.name} was pressed")

# 注册一个键盘事件
keyboard.on_press(on_key_event)

update_frame()